package com.xuecheng.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.feignclient.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.mapper.XcUserRoleMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.model.po.XcUserRole;
import com.xuecheng.ucenter.service.AuthService;
import com.xuecheng.ucenter.service.WxAuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * @ClassName: PasswordAuthServiceImpl
 * @Description: 账号密码认证
 * @Author: Huang Yao
 * @CreateTime: 2024-07-17 15:54
 * @Version: 1.0
 **/
@Slf4j
@Service(value = "Wx_authservice")
public class WxAuthServiceImpl implements AuthService, WxAuthService {


    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private XcUserRoleMapper xcUserRoleMapper;

    @Autowired
    private XcUserMapper xcUserMapper;
    @Autowired
    private WxAuthService currrentproxy;

    @Value("${weixin.appid}")
    String appid;
    @Value("${weixin.secret}")
    String secret;
    @Value("weixin.wxUrlTemplate")
    String wxUrl_template;
    @Value("weixin.wxUrlUserInfoTemplate")
    String wxUrl_userinfo_template;
    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {

        XcUserExt userExt = new XcUserExt();
        userExt.setUsername("t1");
        return userExt;
    }

    @Override
    public XcUser wxAuth(String code) {
        Map<String, String> access_token_map = getAccessToken(code);
        if(CollectionUtils.isEmpty(access_token_map)){
            return null;
        }
        String openid = access_token_map.get("openid");
        String accessToken = access_token_map.get("access_token");
        log.info("微信用户的openid:{},access_token:{}",openid,accessToken);
        Map<String, String> userinfo_map = getUserInfo(accessToken, openid);
        if(userinfo_map == null ) return null;
        //保存到数据库
        XcUser xcUser = currrentproxy.addWxUser(userinfo_map);
        return xcUser;
    }

    private Map<String,String> getAccessToken(String code){
        String wxUrl = String.format(wxUrl_template,code,secret);
        log.info("调用微信接口申请access_token, url:{}", wxUrl);
        ResponseEntity<String> exchange = restTemplate.exchange(wxUrl, HttpMethod.POST, null, String.class);
        String result = exchange.getBody();
        log.info("调用微信接口申请access_token: 返回值:{}", result);
        Map<String,String> map = JSON.parseObject(result, Map.class);
        return map;
    }

    private Map<String,String> getUserInfo(String accessToken,String openid){
        String wxInfoUrl = String.format(wxUrl_userinfo_template, accessToken, openid);
        ResponseEntity<String> exchange = restTemplate.exchange(wxInfoUrl, HttpMethod.POST, null, String.class);
        // 防止乱码进行转码
        String result = new String(Objects.requireNonNull(exchange.getBody()).getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        log.info("调用微信接口申请access_token: 返回值:{}", result);
        return JSON.parseObject(result, Map.class);
    }

    @Transactional
    public XcUser addWxUser(Map userInfo_map){
        String unionid = userInfo_map.get("unionid").toString();
        //根据unionid查询数据库
        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>()
                .eq(XcUser::getWxUnionid, unionid));
        if(xcUser != null){
            return xcUser;
        }
        //使用UUID生成用户id
        String userId = UUID.randomUUID().toString();
        xcUser = new XcUser();
        xcUser.setWxUnionid(unionid);
        xcUser.setId(userId);
        //记录从微信得到的昵称
        xcUser.setNickname(userInfo_map.get("nickName").toString());
        xcUser.setNickname(userInfo_map.get("nickname").toString());
        xcUser.setUserpic(userInfo_map.get("headimgurl").toString());
        xcUser.setName(userInfo_map.get("nickname").toString());
        //使用unionid作为账号和密码
        xcUser.setUsername(unionid);
        xcUser.setPassword(unionid);
        xcUser.setUtype("101001");//学生类型
        xcUser.setStatus("1");//用户状态
        xcUser.setCreateTime(LocalDateTime.now());
        xcUserMapper.insert(xcUser);
        XcUserRole xcUserRole = new XcUserRole();
        xcUserRole.setUserId(userId);
        xcUserRole.setUserId(unionid);
        xcUserRole.setRoleId("17");
        xcUserRole.setCreateTime(LocalDateTime.now());
        xcUserRoleMapper.insert(xcUserRole);
        return xcUser;
    }
}
